package com.menggudf.controller;

import com.alibaba.fastjson.JSONPath;
import com.alibaba.nls.client.AccessToken;
import com.menggudf.common.utils.HttpUtil;
import com.menggudf.model.ResultModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * 手机端用户controller
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/nls")
public class AliNLSController {

    String accessToken = "58636ed9195e4da49f73742f4b8ad69a";
    String appkey = "QP5dvm6jknwAQ93d";
    String ALIYUN_AK_ID = "LTAI5tB336RpCCNGA8tsD5Bk";
    String ALIYUN_AK_SECRET = "PawDWzQOEjG65JDgn46JidCtsaBVx5";
    boolean enablePunctuationPrediction = true;
    boolean enableInverseTextNormalization = true;
    boolean enableVoiceDetection = false;
    String format = "mp3";

    //String fileN = "D://";
    String fileN = "/root";

    @RequestMapping("trans")
    @ResponseBody
    public ResultModel trans(
            HttpServletRequest request1,
            HttpServletResponse response1,
            HttpSession httpSession1,
            @RequestParam MultipartFile file) throws IOException {

        String fileName = fileN + File.separator + "mp3temp" + File.separator + System.currentTimeMillis() + ".mp3";
        File f1 = new File(fileName);
        file.transferTo(f1);

        AccessToken accessToken = new AccessToken(ALIYUN_AK_ID, ALIYUN_AK_SECRET);
        accessToken.apply();
        String token = accessToken.getToken();
        long expireTime = accessToken.getExpireTime();

        /**
         * 设置HTTPS RESTful POST请求：
         * 1.使用HTTPS协议。
         * 2.语音识别服务域名：nls-gateway-cn-shanghai.aliyuncs.com。
         * 3.语音识别接口请求路径：/stream/v1/asr。
         * 4.设置必选请求参数：appkey、format、sample_rate。
         * 5.设置可选请求参数：enable_punctuation_prediction、enable_inverse_text_normalization、enable_voice_detection。
         */
        String url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr";
        String request = url;
        request = request + "?appkey=" + appkey;
        request = request + "&format=" + format;
        request = request + "&sample_rate=" + 16000;
        if (enablePunctuationPrediction) {
            request = request + "&enable_punctuation_prediction=" + true;
        }
        if (enableInverseTextNormalization) {
            request = request + "&enable_inverse_text_normalization=" + true;
        }
        if (enableVoiceDetection) {
            request = request + "&enable_voice_detection=" + true;
        }

        System.out.println("Request: " + request);

        /**
         * 设置HTTPS头部字段：
         * 1.鉴权参数。
         * 2.Content-Type：application/octet-stream。
         */
        HashMap<String, String> headers = new HashMap<String, String>();
        //headers.put("X-NLS-Token", this.accessToken);
        headers.put("X-NLS-Token", token);
        headers.put("Content-Type", "application/octet-stream");

        /**
         * 发送HTTPS POST请求，返回服务端的响应。
         */
        String response = HttpUtil.sendPostFile(request, headers, fileName);

        //String response = HttpUtil.sendPostData(request, headers, file.getBytes());

        f1.delete();

        if (response != null) {
            System.out.println("Response: " + response);
            String result = JSONPath.read(response, "result").toString();
            System.out.println("识别结果：" + result);
            return ResultModel.success("识别成功",result);
        }
        else {
            System.err.println("识别失败!");
            return ResultModel.fail("识别失败",null);
        }

    }


    
}
